﻿using System.Collections.Generic;
using System.Linq;
using LinFu.IoC.Configuration;

namespace CoreEx.MicroMapper.Implementation
{
    [Implements(typeof(IAccessorInfoMatcher),LifecycleType.OncePerRequest)]
    public class AccessorInfoMatcher : IAccessorInfoMatcher
    {
        public IEnumerable<IAccessorInfoMatch> Match(IEnumerable<IAccessorInfo> sourceAccessors,
                                                     IEnumerable<IAccessorInfo> targetAccessors)
        {
            
            
            var matches =  sourceAccessors.Join(targetAccessors, o => o.Name.ToLowerInvariant(), i => i.Name.ToLowerInvariant(),
                                        (o, i) =>
                                        (IAccessorInfoMatch)
                                        new AccessorInfoMatch {SourceAccessorInfo = o, TargetAccessorInfo = i});

            if (matches.Count() == 0 && sourceAccessors.Count() > 0)
                return
                    sourceAccessors.Select(a => (IAccessorInfoMatch)new AccessorInfoMatch() {SourceAccessorInfo = a, TargetAccessorInfo = a});

            if (matches.Count() == 0 && targetAccessors.Count() > 0)
                return
                    targetAccessors.Select(a => (IAccessorInfoMatch)new AccessorInfoMatch() { SourceAccessorInfo = a, TargetAccessorInfo = a });
            
            return matches;
        }
    }
}
